package com.julu.o2o.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.core.Controller;
/**
 * cooke工具类
 * @author yangtonggan
 * @date 2016-4-11
 */
public class CookieUtil {
    public static final String SESSION_ID = "sessionId";
    
    /**
     * 从Cookie中读取sessionID
     * @param req
     * @return
     */
	public static String getSessionId(Controller c){
		/*
		HttpServletRequest req = c.getRequest();
		HttpServletResponse rep = c.getResponse();
		String sessionId = req.getParameter("sessionId");
		if(StringUtil.notEmpty(sessionId)){
			return sessionId;
		}
		Cookie[] cookies = req.getCookies();		
		if(cookies != null){
			for(Cookie cooke :cookies){
				if(cooke.getName().equalsIgnoreCase(SESSION_ID)){
					sessionId =  cooke.getValue();
					break;
				}
			}
		}
		
		if(StringUtil.isEmpty(sessionId)){
			SessionIdGenerator generator = new UUIDSessionIdGenerator();
			sessionId = generator.genaeratorSessionId();
			writeSessionId(rep,sessionId);
		}	
		*/	
		HttpServletRequest req = c.getRequest();
		String sessionId = (String)req.getSession(true).getId();
		/*
		if(sessionId == null){
			SessionIdGenerator generator = new UUIDSessionIdGenerator();
			sessionId = generator.genaeratorSessionId();
			req.getSession().setAttribute(SESSION_ID, sessionId);
		}
		*/
		return sessionId;	
		
	}
	
	/**
	 * 把SessionID写入Cookie中
	 */
	public static void writeSessionId(HttpServletResponse rep,String sessionId){
		Cookie cookie = new Cookie(SESSION_ID,sessionId);	
		cookie.setMaxAge(60*60*24*365);
		cookie.setDomain("localhost");
		rep.addCookie(cookie);
	}
}
